﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WHC.Hotel.Entity;
using WHC.Hotel.BLL;
using WHC.OrderWater.Commons;


namespace WHC.Hotel.UI
{
    public partial class FrmEditRoomRegister : BaseForm
    {
        public RoomInfo RoomInfo = null;
        private OrderInfo orderInfo = null;

        public FrmEditRoomRegister()
        {
            InitializeComponent();

            InitDictItems();
        }

        private void InitDictItems()
        {
            this.txtCustomerType.Items.Clear();
            this.txtCustomerType.Items.AddRange(DictItemUtil.GetCustomerType());
            if (this.txtCustomerType.Items.Count > 0)
            {
                this.txtCustomerType.SelectedIndex = 0;
            }

            this.txtCardType.Items.Clear();
            this.txtCardType.Items.AddRange(DictItemUtil.GetIDCarType());
            if (this.txtCardType.Items.Count > 0)
            {
                this.txtCardType.SelectedIndex = 0;
            }

            this.txtSource.Items.Clear();
            this.txtSource.Items.AddRange(DictItemUtil.GetCustomerSource());
            if (this.txtSource.Items.Count > 0)
            {
                this.txtSource.SelectedIndex = 0;
            }
        }

        private void FrmEditOrder_Load(object sender, EventArgs e)
        {
            this.txtPrLivedDays.Focus();

            if (RoomInfo != null)
            {
                this.lblRoomNo.Text = RoomInfo.RoomNo;
                this.lblRoomType.Text = RoomInfo.RoomType;

                orderInfo = BLLFactory<Order>.Instance.GetCurrentOrder(RoomInfo.RoomNo);
                if (orderInfo == null)
                    return;

                this.lblDeposit.Text = orderInfo.DepositMoney.ToString("C2");
                this.lblDiscount.Text = orderInfo.DiscountRate.ToString("f2");
                this.lblDiscountPrice.Text = orderInfo.DiscountPrice.ToString("C2");
                this.lblOriginalPrice.Text = orderInfo.OriginalPrice.ToString("C2");
                this.lblPayType.Text = orderInfo.PayType;
                this.chkPartTime.Checked = orderInfo.IsPartTime;

                CustomerInfo customerInfo = BLLFactory<Customer>.Instance.FindByID(orderInfo.Customer_ID);
                this.txtAddress.Text = customerInfo.Address;
                this.txtCardType.Text = customerInfo.IDCarType;
                this.txtCompanyName.Text = customerInfo.CompanyName;
                this.txtCustomerType.Text = customerInfo.CustomerType;
                this.txtIDNumber.Text = customerInfo.IDNumber;
                this.txtName.Text = orderInfo.CustomerName;
                this.txtNote.Text = customerInfo.Note;
                this.txtOrderNo.Text = orderInfo.OrderNo;
                this.txtPersons.Text = orderInfo.Persons.ToString();
                this.txtPrLivedDays.Text = orderInfo.PreLivedDays.ToString();
                this.txtSex.Text = customerInfo.Sex;
                this.txtSource.Text = customerInfo.Source;
                this.txtTelephone.Text = customerInfo.Telephone;
                UseTime.Text = orderInfo.CreateDate.ToShortDateString();
                txtHour.Text = orderInfo.CreateDate.Hour.ToString("D2");
                txtMinute.Text = orderInfo.CreateDate.Minute.ToString("D2");
                leaveTime.Text = orderInfo.CreateDate.AddDays(orderInfo.PreLivedDays).ToString("yyyy-MM-dd")+" 14:00";


                RefreshAddedItems();
            }
        }

        private void RefreshAddedItems()
        {
            this.lsvAdded.Items.Clear();
            List<OrderInfo> orderList = BLLFactory<Order>.Instance.GetRelatedOrders(RoomInfo.RoomNo);
            for(int i=0; i<orderList.Count; i++)
            {
                OrderInfo info = orderList[i]; 
                ListViewItem lvItem = new ListViewItem((i+1).ToString());
                lvItem.SubItems.Add(info.RoomNo);
                lvItem.SubItems.Add(info.RoomType);
                lvItem.SubItems.Add(info.OriginalPrice.ToString("C2"));
                lvItem.SubItems.Add(info.DiscountRate.ToString("f2"));
                lvItem.SubItems.Add(info.DiscountPrice.ToString("C2"));

                this.lsvAdded.Items.Add(lvItem);
            }
        }

        private void ChangeCustomer(string customerID)
        {
            if (!string.IsNullOrEmpty(customerID))
            {
                CustomerInfo info = BLLFactory<Customer>.Instance.FindByID(customerID);
                if (info != null)
                {
                    this.txtAddress.Text = info.Address;
                    this.txtCardType.Text = info.IDCarType;
                    this.txtCompanyName.Text = info.CompanyName;

                    int i = txtCustomerType.FindStringExact(info.CustomerType);
                    this.txtCustomerType.SelectedIndex = i;

                    this.txtIDNumber.Text = info.IDNumber;
                    this.txtName.Text = info.Name;
                    this.txtSex.Text = info.Sex;
                    this.txtTelephone.Text = info.Telephone;
                    this.txtSource.Text = info.Source;
                    this.txtNote.Text = info.Note;
                    
                }
            }
        }

        private void btnNameSearch_Click(object sender, EventArgs e)
        {
            FrmCustomerSearch dlg = new FrmCustomerSearch();
            dlg.txtName.Text = this.txtName.Text;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (!string.IsNullOrEmpty(dlg.SelectedID))
                {
                    ChangeCustomer(dlg.SelectedID);
                }
            }
        }
        
        private void btnIDSearch_Click(object sender, EventArgs e)
        {
            FrmCustomerSearch dlg = new FrmCustomerSearch();
            dlg.txtName.Text = this.txtIDNumber.Text;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (!string.IsNullOrEmpty(dlg.SelectedID))
                {
                    ChangeCustomer(dlg.SelectedID);
                }
            }
        }

        private void btnTelSearch_Click(object sender, EventArgs e)
        {
            FrmCustomerSearch dlg = new FrmCustomerSearch();
            dlg.txtName.Text = this.txtTelephone.Text;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (!string.IsNullOrEmpty(dlg.SelectedID))
                {
                    ChangeCustomer(dlg.SelectedID);
                }
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            #region 输入检查

            this.DialogResult = DialogResult.None;
            if (this.txtName.Text.Trim().Length == 0)
            {
                MessageUtil.ShowTips("请输入主客姓名");
                this.txtName.Focus();
                return;
            }
            else if (this.txtIDNumber.Text.Trim().Length == 0)
            {
                MessageUtil.ShowTips("请输入证件编码");
                this.txtIDNumber.Focus();
                return;
            }
            else if (this.txtCustomerType.Text.Length == 0)
            {
                MessageUtil.ShowTips("请选择宾客类型");
                this.txtCustomerType.Focus();
                return;
            }
            if (txtCardType.Text == "身份证")
            {

                if (!Public.CheckIDCard(txtIDNumber.Text))
                {

                    MessageUtil.ShowTips("身份证号码不正确");
                    this.txtIDNumber.Focus();
                    return;

                }



            }

            string userName = this.txtName.Text.Trim();
            CustomerInfo existInfo = BLLFactory<Customer>.Instance.CheckUser(userName, this.txtIDNumber.Text);
            if (existInfo == null)
            {
                #region 确保数据库中存在指定的记录
                string message = string.Format("宾客信息在数据库中不存在，需要添加到数据库中才能修改订单。\r\n您是否确定增加到数据库中？");
                if (MessageUtil.ShowYesNoAndTips(message) == DialogResult.No)
                {
                    return;
                }
                else
                {
                    try
                    {
                        bool success = AddCustomerToDB();
                        if (!success)
                        {
                            MessageUtil.ShowWarning("客户信息添加未成功");
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("客户信息添加出错", ex);
                        MessageUtil.ShowWarning("客户信息添加出错");
                        return;
                    }
                } 
                #endregion
            }

            #endregion

            #region 保存订单
            //万事俱备，只欠东风
            existInfo = BLLFactory<Customer>.Instance.CheckUser(userName, this.txtIDNumber.Text);
            if (existInfo != null)
            {
                try
                {
                    //改变订单的客户信息即可
                    orderInfo.CustomerName = this.txtName.Text;
                    orderInfo.Customer_ID = existInfo.ID;
                    orderInfo.PreLivedDays = Convert.ToInt32(this.txtPrLivedDays.Text);
                    orderInfo.Persons = Convert.ToInt32(this.txtPersons.Text);
                    orderInfo.OrderNo = this.txtOrderNo.Text;
                    orderInfo.CreateDate = Convert.ToDateTime(UseTime.Text.Replace("/", "-") + " " + txtHour.Text + ":" + txtMinute.Text + ":" + orderInfo.CreateDate.Second.ToString());

                    bool result = BLLFactory<Order>.Instance.Update(orderInfo, orderInfo.ID.ToString());
                    if (result)
                    {
                        MessageUtil.ShowTips("保存订单成功");
                        this.DialogResult = DialogResult.OK;
                    }
                    else
                    {
                        MessageUtil.ShowTips("保存订单失败");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    MessageUtil.ShowError("保存订单出错：" + ex.Message);
                }
            } 
            #endregion
        }

        private bool AddCustomerToDB()
        {
            CustomerInfo info = new CustomerInfo();
            info.Name = this.txtName.Text.Trim();
            info.Address = this.txtAddress.Text;
            info.CompanyName = this.txtCompanyName.Text;
            info.CustomerType = this.txtCustomerType.Text;
            info.IDCarType = this.txtCardType.Text;
            info.IDNumber = this.txtIDNumber.Text;
            info.Note = this.txtNote.Text;
            info.RegistrationDate = DateTime.Now;
            info.Sex = this.txtSex.Text;
            info.Source = this.txtSource.Text;
            info.Telephone = this.txtTelephone.Text;

            return BLLFactory<Customer>.Instance.Insert(info);
        }

     

        private void txtPrLivedDays_TextChanged(object sender, EventArgs e)
        {

            leaveTime.Text = Convert.ToDateTime(UseTime.Text).AddDays(Convert.ToInt32(txtPrLivedDays.Text)).ToString("yyyy-MM-dd") + " 14:00";

        }

        private void UseTime_CloseUp(object sender, EventArgs e)
        {
            leaveTime.Text = Convert.ToDateTime(UseTime.Text).AddDays(Convert.ToInt32(txtPrLivedDays.Text)).ToString("yyyy-MM-dd") + " 14:00";

        }
    }

}
